var app;
var contextPath = "";
window.onload = function (ev) {
    app = new Vue({
        el: "#app",
        data: {
            mineInfo: {},
            messageReceiver: {},
            //消息缓存，切换tab的时候使用缓存
            messages: {},
            //记录每个dialog的最大messageId，key为dialogId，下次以增量获取，暂未使用
            dialogMessageMaxId: {},
            //输入框在中正在输入的消息
            typingMessage: "",
            activeUserName: "",
            activeDialogId: -1,
            activeDialogGroupName: "",
            menuActiveTab: 0,
            userListActiveTab: 0,
            dialogList: [],
            dialog: {current: [], history: []},
            activeMessages: []
        },
        updated: function () {
            // 更新完成后，默认让聊天框滚动条在最底部
            var div = document.getElementById("dialog_" + this.activeDialogId);
            if (div) div.scrollTop = div.scrollHeight;
        },
        created: function () {
            this.initDialogList(0);
            this.initMineInfo();
        },
        mounted: function () {
            // 页面加载完之后开始刷新消息
            this.pollingMessage();
        },
        methods: {
            changeDialogListTab: function (index, dialog) {
                var _this = this;
                this.userListActiveTab = index;
                //如果有新消息标记，则重新重数据库拉取dialog信息
                if (dialog.newFlag == 1) {
                    axios({
                        url: contextPath + "/dialog/getById/" + dialog.id,
                        method: "get",
                        headers: {token: "uid"}
                    }).then(function (response) {
                        if (response.data.code == 0) {
                            var d = response.data.resultBody.body[0];
                            for(var idx = 0;idx < _this.dialog.current.length;idx++) {
                                if(_this.dialog.current[idx].id == d.id) {
                                    //用新查询出来的dialog数据替换新消息数据
                                    _this.dialog.current[idx] = d;
                                    _this.dialogList = _this.dialog.current;
                                    break;
                                }
                            }
                            // 标记为已读
                            d.readFlag = 1;
                            _this.messageReceiver = {id: d.userId, headImg: d.headImg};
                            _this.activeDialogId = d.id;
                            _this.activeUserName = d.nickname;
                            _this.activeDialogGroupName = d.groupName;
                        }
                    }).catch(function (reason) {
                        console.log(reason)
                    });
                }
                if (dialog.newFlag != 1) {
                    // 标记为已读
                    dialog.readFlag = 1;
                    this.messageReceiver = {id: dialog.userId, headImg: dialog.headImg};
                    this.activeDialogId = dialog.id;
                    this.activeUserName = dialog.nickname;
                    this.activeDialogGroupName = dialog.groupName;
                }
                if (this.messages[dialog.id]) {
                    this.activeMessages = this.messages[dialog.id];
                } else {
                    //如果messages中没有，就全量获取
                    axios({
                        url: contextPath + "/message/init/" + dialog.id,
                        method: "get",
                        headers: {token: "uid"}
                    }).then(function (response) {
                        _this.activeMessages = response.data.resultBody.body;
                        _this.messages[dialog.id] = _this.activeMessages;
                    }).catch(function (reason) {
                        console.log(reason)
                    });
                }
            },
            sendMessage: function () {
                if (!this.messageReceiver.id || this.activeDialogId == -1) {
                    alert("请选择一个会话");
                    return;
                }
                if (this.typingMessage.length == 0) {
                    alert("消息内容不能为空");
                    return;
                }
                var _this = this;
                var msg = {
                    content: this.typingMessage,
                    sender: 1,
                    type: 0,
                    dialogId: this.activeDialogId,
                    createTime: dateFormat(new Date(), "yyyy-MM-dd HH:mm:ss")
                };
                axios({
                    url: contextPath + "/message/send/" + _this.messageReceiver.id,
                    method: "post",
                    data: msg,
                    contentType: "application/json; charset=utf-8",
                    headers: {token: "uid"}
                }).then(function (response) {
                    var code = response.data.code;
                    if (code == 0) {
                        _this.activeMessages.push(msg);
                        //messages里面的key和上面是同一个地址，重复添加造成消息重复
                        // this.messages[this.activeDialogId].push(msg);
                        //清空输入框
                        _this.typingMessage = "";
                    }
                }).catch(function (reason) {
                    alert("消息发送失败");
                })
            },
            initDialogList: function (index) {
                this.menuActiveTab = index;
                var key = index == 0 ? "current" : "history";
                // 如果有缓存用缓存
                if (this.dialog[key].length > 0) {
                    this.dialogList = this.dialog[key];
                    return;
                }
                var _this = this;
                var url = index == 0 ? "/dialog/current" : "/dialog/history";
                //初始化dialog列表
                axios({
                    url: contextPath + url,
                    method: "get",
                    headers: {token: "uid"}
                }).then(function (response) {
                    var code = response.data.code;
                    if (code == 0) {
                        _this.dialogList = response.data.resultBody.body;
                        _this.dialog[key] = response.data.resultBody.body;
                    }
                    //第一次请求网络时，默认打开列表中第一条会话
                    if (_this.dialogList.length > 0) {
                        _this.changeDialogListTab(0, _this.dialogList[0])
                    }
                }).catch(function (reason) {
                    console.log(reason)
                });
            },
            initHistoryDialogList: function () {
                var _this = this;
                axios({
                    url: contextPath + "/dialog/history",
                    method: "get",
                    headers: {token: "uid"}
                }).then(function (response) {
                    _this.historyDialogList = response.data.resultBody.body;
                    for (var dialog in _this.historyDialogList) {
                        dialog.readFlag = 1;
                    }
                }).catch(function (reason) {
                    console.log(reason)
                });
            },
            initMineInfo: function () {
                var _this = this;
                axios({
                    url: contextPath + "/kefu/info",
                    method: "get",
                    headers: {token: "uid"}
                }).then(function (response) {
                    _this.mineInfo = response.data.resultBody.body;
                }).catch(function (reason) {
                    console.log(reason)
                });
            },
            pollingMessage: function () {
                var _this = this;
                axios({
                    url: contextPath + "/message/polling",
                    method: "get",
                    headers: {token: "uid"}
                }).then(function (response) {
                    var dialogMapList = response.data.resultBody.body;
                    if (dialogMapList[_this.activeDialogId]) {
                        _this.activeMessages = dialogMapList[_this.activeDialogId];
                    }
                    for (var key in dialogMapList) {
                        _this.messages[key] = dialogMapList[key];
                        if (key == _this.activeDialogId) {
                            continue;
                        }
                        for (var idx = 0; idx < _this.dialogList.length; idx++) {
                            if (_this.dialogList[idx].id == key) {
                                // 标记该会话为未读
                                _this.dialogList[idx].readFlag = 0;
                                break;
                            }
                        }
                        if (idx == _this.dialogList.length) {
                            //走到这里说明是新会话，新会话是需要重新拉取真实头像等信息，这个留在客服点击该会话时获取，这里使用特别的新会话默认头像做以区分，并添加会话列表头部
                            _this.dialog.current.unshift({
                                id: key,
                                newFlag: 1,
                                nickname: "新消息",
                                readFlag: 0,
                                headImg: "img/new_dialog.png"
                            });
                            // 因为是添加到头部，所以将当前活动的会话会被后移一位，将当前活动的tab数加1
                            _this.userListActiveTab++;
                        }
                    }
                    setTimeout(_this.pollingMessage, 1000);
                }).catch(function (reason) {
                    console.log(reason);
                    setTimeout(_this.pollingMessage, 1000);
                });
            },
            triggerUpload: function () {
                this.$refs.fileUploadInput.click();
            },
            fileUpload: function () {
                var _this = this;
                //创建要提交的表单
                var formData = new FormData();
                //这里用了prop("files")[0]取出文件，这里是files哦，不是input的name[file]
                var f = this.$refs.fileUploadInput.files[0];
                formData.append("file", f);
                formData.append("sender", 1);
                formData.append("type", 1);
                formData.append("dialogId", this.activeDialogId);
                axios({
                    url: contextPath + "/message/sendFile/" + _this.messageReceiver.id,
                    method: "post",
                    data: formData,
                    headers: {
                        token: "uid",
                        'Content-Type': 'multipart/form-data'
                    }
                }).then(function (response) {
                    var code = response.data.code;
                    if (code == 0) {
                        _this.activeMessages.push(response.data.resultBody.body);
                    }
                }).catch(function (reason) {
                    console.log(reason)
                });
                this.$refs.fileUploadInput.value = "";
            },
            closeActiveDialog: function () {
                var _this = this;
                var closeId = _this.activeDialogId;
                axios({
                    url: contextPath + "/dialog/close/" + closeId,
                    method: "post",
                    headers: {
                        token: "uid",
                    }
                }).then(function (response) {
                    var code = response.data.code;
                    if (code == 0) {
                        for (var idx = 0; idx < _this.dialog.current.length; idx++) {
                            if (_this.dialog.current[idx].id == closeId) {
                                //移除当前会话
                                _this.dialog.current.splice(idx, 1);
                                _this.dialogList = _this.dialog.current;
                                //删除会话的消息记录key
                                delete _this.messages[closeId];
                                if (_this.dialogList.length > 0) {
                                    _this.changeDialogListTab(0, _this.dialogList[0]);
                                } else {
                                    _this.activeDialogId = -1;
                                }
                                break;
                            }
                        }
                    }
                }).catch(function (reason) {
                    console.log(reason)
                });
            },
            quit: function () {
                alert("quit:id=" + this.mineInfo.id);
            }
        }
    });
}